
import {login, logout, getInfo} from '@/api/acl/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter,allAsyncRoutes,constantRoutes,anyRoute} from '@/router'
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'

//根据返回的路由名称数组过滤用户真正的异步路由数组  5
function filterUserAsyncRoutes(allAsyncRoutes,routeNames){
  const result = allAsyncRoutes.filter(item => {
    if(routeNames.indexOf(item.name) !== -1){
      if(item.children && item.children.length > 0){
        item.children = filterUserAsyncRoutes(item.children,routeNames)
      }
      return true
    }
  })

  return result
}

const state ={
  token:localStorage.getItem('token'),
  name: '',
  avatar: '',
  buttons:[],
  roles:[],
  asyncRoutes:[],
  routes:[] 
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userinfo) => {
    state.name = userinfo.name
    state.avatar = userinfo.avatar
    state.buttons = userinfo.buttons
    state.roles = userinfo.roles
  },
   SET_STATE(state){
    state.token=''
    state.name=''
     state.avatar=''
  },
  SET_ROUTES(state,asyncRoutes){
    state.asyncRoutes = asyncRoutes
    console.log( 2)
    state.routes = constantRoutes.concat(asyncRoutes,anyRoute) 
    console.log( 2)
    router.addRoutes([...asyncRoutes,anyRoute]) //动态注册路由
  }
}

const actions = {
  async login({commit},userInfo){
    const {username,password}=userInfo
    const result = await login({ username: username.trim(), password: password })
    if(result.code===200||result.code===20000){
      commit('SET_TOKEN',result.data.token)
      localStorage.setItem('token',result.data.token)
    }
  },


  async getInfo({commit,state}){
    const result = await getInfo(state.token)
    console.log(1);
    if(result.code===200||result.code===20000){
      commit('SET_USERINFO',result.data)
      commit('SET_ROUTES',cloneDeep(filterUserAsyncRoutes(allAsyncRoutes,result.data.routes)))
    }
   
  },

  
async logout({commit,state}){
  const result = await logout(state.token)
  if(result.code===200||result.code===20000){
    localStorage.removeItem('token')//验证token
    resetRouter()//这是重置路由
    commit('RESET_STATE')
  }
},

 resetToken({commit}){
 localStorage.removeItem('token')
  commit('RESET_STATE')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}






